<?php
namespace app\macht\controller;
use app\common\model\CardStore;
use app\common\model\Agent;
use app\common\model\Momerchant;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
class Store extends MachBase
{
    //首页
    public function storelist(){
        $CardStore = new CardStore();
        $list = $CardStore->select();
        $this->assign('list',$list);
        return $this->fetch();
    }

    //添加
    public function addstore(){
        //门店创建
        if (Request()->isPost()) {
            $arrp = request()->post();
            $data = $this->creatdata($arrp);
            //当前授权APPID
            $options = $this->options();
            $weObj = new Wxobjopen($options);
            $res = $weObj->creatStore($data);
            if($res['errcode'] == 0){
                $adata = array(
                    'sid'=>$arrp['sid'],
                    'poi_id'=>$arrp['poi_id'],
                    'business_name'=>$arrp['business_name'],
                    'branch_name'=>$arrp['branch_name'],
                    'province'=>$arrp['province'],
                    'city'=>$arrp['city'],
                    'district'=>$arrp['district'],
                    'address'=>$arrp['address'],
                    'telephone'=>$arrp['telephone'],
                    'categories'=>$arrp['categories'],
                    'offset_type'=>$arrp['offset_type'],
                    'longitude'=>$arrp['longitude'],
                    'latitude'=>$arrp['latitude'],
                    'photo_list'=>$arrp['photo_list'],
                    'recommend'=>$arrp['recommend'],
                    'special'=>$arrp['special'],
                    'introduction'=>$arrp['introduction'],
                    'open_time'=>$arrp['open_time'],
                    'avg_price'=>$arrp['avg_price'],
                    'state'=>1,
                    'create_time'=>time(),
                );
                $CardStore = new CardStore();
                $CardStore->allowField(true)->save($adata);
                $this->success('创建成功', 'store/index');
            }else{
                $this->error('创建失败', 'store/index');
            }
        }else{
            return $this->fetch();
        }
    }

    //修改
    public function editstore($id){
        if (Request()->isPost()) {
            $arrp = request()->post();
            $data = $this->editdata($arrp);
            //当前授权APPID
            $options = $this->options();
            $weObj = new Wxobjopen($options);
            $res = $weObj->editStore($data);
            if($res['errcode'] == 0){
                $adata = array(
                    'sid'=>$arrp['sid'],
                    'poi_id'=>$arrp['poi_id'],
                    'business_name'=>$arrp['business_name'],
                    'branch_name'=>$arrp['branch_name'],
                    'province'=>$arrp['province'],
                    'city'=>$arrp['city'],
                    'district'=>$arrp['district'],
                    'address'=>$arrp['address'],
                    'telephone'=>$arrp['telephone'],
                    'categories'=>$arrp['categories'],
                    'offset_type'=>$arrp['offset_type'],
                    'longitude'=>$arrp['longitude'],
                    'latitude'=>$arrp['latitude'],
                    'photo_list'=>$arrp['photo_list'],
                    'recommend'=>$arrp['recommend'],
                    'special'=>$arrp['special'],
                    'introduction'=>$arrp['introduction'],
                    'open_time'=>$arrp['open_time'],
                    'avg_price'=>$arrp['avg_price'],
                    'state'=>1,
                    'create_time'=>time(),
                );
                $CardStore = new CardStore();
                $CardStore->save($adata,['id',$id]);
                $this->success('修改成功', 'store/index');
            }else{
                $this->error('修改成功', 'store/index');
            }
        }else{
            $CardStore = new CardStore();
            $info = $CardStore->where(['id'=>$id])->find();
            $this->assign('info',$info);
            return $this->fetch();
        }
    }

    //同步官方门店
    public function tbstore(){
        $arr = request()->param();
        $Merchant = new Merchant();
        $arrp = $Merchant->where(array('id' => $arr['id']))->relation('MerchantContent')->find();
        $top_mid = Session::get('login_top_mid');
        $Momerchant = new Momerchant();
        $momach = $Momerchant->where('id',$top_mid)->find();
        $data = array(
            'sid' => $top_mid,
            'business_name'=>$momach['merchant_name'],
            'branch_name'=>$arrp['branch_name'],
            'province'=>$arrp['province'],
            'city'=>$arrp['city'],
            'district'=>$arrp['district'],
            'address'=>$arrp['MerchantContent']['address'],
            'telephone'=>$arrp['MerchantContent']['tel'],
            'categories'=>$arrp['categories'],
            'offset_type'=>$arrp['offset_type'],
            'longitude'=>$arrp['longitude'],
            'latitude'=>$arrp['latitude'],
//            'photo_list'=>$arrp['photo_list'],
//            'recommend'=>$arrp['recommend'],
//            'special'=>$arrp['special'],
//            'introduction'=>$arrp['introduction'],
//            'open_time'=>$arrp['open_time'],
//            'avg_price'=>$arrp['avg_price'],
            'pass_statu'=>2,               //待审核
            'create_time'=>time(),
        );
        $res = in_array('',$data);
        if ($res){
            $this->success('门店资料未完成,无法同步。','mach/machlist');
        }
        $options = $this->option($arr['id']);
        $weObj = new Wxobjopen($options);
        $res = $weObj->creatStore($data);
        if($res['errcode'] == 0){
            $adata['poi_id'] = $res['poi_id'];
            $resu = $Merchant->save($adata,['id'=>$arr['id']]);
            if ($resu){
                $this->success('同步创建成功，等待审核！','mach/machlist');
            }else{
                $this->error('同步创建失败！','mach/machlist');
            }
        }
    }


    //详情
    public function storeInfo($id){
        $CardStore = new CardStore();
        $info = $CardStore->where('id',$id)->find();
        $this->assign('info',$info);
        return $this->fetch();
    }

    //删除
    public function delStore($sid, $poi_id,$id){
        $map['poi_id'] = $poi_id;
        $map['sid'] = $sid;
        $data = array(
            'poi_id'=>$poi_id,
        );
        //当前授权APPID
        $options= $this->options();
        $weObj = new Wxobjopen($options);
        $res = $weObj->delStore($data);
        if ($res['errcode'] == 0){
            $ddata['state'] = 0;
            $CardStore = new CardStore();
            $CardStore->where('id',$id)->delete();
            $this->success('删除成功', 'store/index');
        } else {
            $this->error('删除失败', 'store/index');
        }
    }


    //获取类目信息
    public function storeGory(){
        $options= $this->options();
//        var_dump($options);
        $weObj = new Wxobjopen($options);
        $res = $weObj->getStoreGory();
        return json($res);
    }

    //获取坐标地址
    public function getaddress(){
        if (Request()->isAjax()){
            $arrp = request()->post();
            $location = $arrp['lat'] . ',' . $arrp['lng'];
            $data = [
                'location' => $location,
                'get_poi' => '0',
                'key' => 'KNPBZ-RXKWI-SJJGI-5S3HH-AGDS6-Q6BDW'
            ];
            $res = $this->getWsLocation($data);
            if ($res['status'] == 0){
                $result = $res['result'];
                return json($result);
            }else{
                return json(01);
            }
        }
    }

    public function getIpWsLocation()
    {
        if (Request()->isAjax()) {
            $data = [
                'get_poi' => '0',
                'key' => 'KNPBZ-RXKWI-SJJGI-5S3HH-AGDS6-Q6BDW'
            ];
            $ip = request()->ip();
            $url = 'https://apis.map.qq.com/ws/location/v1/ip?ip=' . $ip . '&key=' . $data['key'];
            $result = $this->http_get($url);
            $res = json_decode($result, true);
            if ($res['status'] == 0){
                $result = $res['result'];
//                $result['location']['lat'] = '38.118084';
//                $result['location']['lng'] = '114.566695';
                return json($result);
            }else{
                return json(01);
            }
        }
    }



    public function getWsLocation($data)
    {
        $url = 'https://apis.map.qq.com/ws/geocoder/v1?location=' . $data['location'] . '&key=' . $data['key'] . '&get_poi=' . $data['get_poi'];
        $result = $this->http_get($url);
        return json_decode($result, true);
    }

    private function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
    /*
     *字段处理
     */

    //创建
    public function creatdata($arr){
        //添加处理
        $res = array(
            "business"=>array(
                "base_info"=>array(
                    //             "sid"=>"33788392",                         //门店ID
                    "business_name"=>$arr['business_name'],      //门店名称
                    "branch_name"=>$arr['branch_name'],          //分店名称
                    "province"=>$arr['province'],                //门店所在的省份
                    "city"=>$arr['city'],                        //门店所在的城市
                    "district"=>$arr['district'],                //门店所在地区
                    "address"=>$arr['address'],                  //门店所在的详细街道地址
                    "telephone"=>$arr['telephone'],              //门店的电话
                    "categories"=>array(                         //门店的类型
                        $arr['categories']
                    ),
                    "offset_type"=>$arr['offset_type'],          //坐标类型  ：1 为火星坐标2 为sogou经纬度3 为百度经纬度4 为mapbar经纬度5 为GPS坐6 为sogou墨卡托坐标注：高德经纬度无需转换可直接使用
                    "longitude"=>$arr['longitude'],              //门店所在地理位置的经度
                    "latitude"=>$arr['latitude'],                //门店所在地理位置的纬度

//                    "photo_list"=>[                           //图片列表
//                       $arr['photo_url']
//                    ],
//                    "recommend"=>$arr['recommend'],                   //推荐品
//                    "special"=>$arr['special'],                     //特色服务
//                    "introduction"=>$arr['introduction'],                //商户简介
//                    "open_time"=>$arr['open_time'],                   //营业时间
//                    "avg_price"=>$arr['avg_price']                    //人均价格
                ),
            ),
        );
        return $res;
    }

    //修改
    public function editdata($arr){
        $res = [
            "business"=>[
                "base_info"=>[
                    "sid"=>$arr['telephone'],                    //门店ID
                    "poi_id"=>$arr['poi_id '],                   //门店返回ID
                    "telephone"=>$arr['telephone'],              //门店的电话
//                    "photo_list"=>array(                     //图片列表
//                        $arr['photo_url'],
//                    ),
//                    "recommend"=>$arr['recommend'],                   //推荐品
//                    "special"=>$arr['special'],                     //特色服务
//                    "introduction"=>$arr['introduction'],                //商户简介
//                    "open_time"=>$arr['open_time'],                   //营业时间
//                    "avg_price"=>$arr['avg_price']                    //人均价格
                ],
            ],
        ];
        return $res;
    }

    //获取微信门店类别
    public function getwxstoregory(){
        $options= $this->options();
        $weObj = new Wxobjopen($options);
        $res = $weObj->getStoreGory();
        var_dump($res);
    }

    //获取微信门店
    public function getwxstore(){
        $data = [
            "begin"=>0,
            "limit"=>10
        ];
        $options= $this->options();
        $weObj = new Wxobjopen($options);
        $res = $weObj->getStoreList($data);
        if ($res['errcode'] == 0){
            $list[] = $res['business_list'];
        }elseif($res['errcode'] == 48001){
            $weObj = new Wxobjopen($options);
            $datas = [
                "offset"=>0,
                "limit"=>0
            ];
            $res = $weObj->getStoreListApp($datas);
            var_dump($res);
            if ($res['errcode'] == 0){
                $list[] = $res['business_list'];
            }else{
                $list = $res;
            }
        }else{
            $list = $res;
        }
        return json($list);
    }


    //微信API参数 根据mid获取
    public function options(){
        Session::set('openid', null);
        $System=new System();
        $WxOpen=new WxOpen();
        $Agent=new Agent();
        $top_mid = Session::get('login_top_mid');
        $Momerchant=new Momerchant();
        $momerchantinfo=$Momerchant->where('id',$top_mid)->field('wx_open_id,agent')->find();
        $mab['id'] =$momerchantinfo['wx_open_id'];
//        $config =$System->where(array('id' => 1))->find();
        $config =$Agent->where(array('id' => $momerchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //微信API参数 根据mid获取
    public function option($mid){
        Session::set('openid', null);
        $System=new System();
        $WxOpen=new WxOpen();
        $Agent=new Agent();
        $Merchant=new Merchant();
        $merchantinfo=$Merchant->where('id',$mid)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config =$System->where(array('id' => 1))->find();
        $config =$Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    public function index(){
        $data = [
            ''=>'',
        ];
    }
}
